package com.tn.mqtt;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * @ClassName MQTTListener
 * @Description TODO
 * @Author Yezhongzhu
 * @Date 2021/11/26 9:45
 * @Version v1.0
 **/
@Component
@Slf4j
public class MQTTListener implements ApplicationListener<ContextRefreshedEvent> {
    @Resource
    public MqttConfig mqttConfig;

    private final MQTTConnect server;

    @Autowired
    public MQTTListener(MQTTConnect server) {
        this.server = server;
    }

    @Override
    public void onApplicationEvent(ContextRefreshedEvent contextRefreshedEvent) {
        try {
            server.setMqttClient(mqttConfig.getUserName(), mqttConfig.getPassWord(), new Callback());
            server.sub(mqttConfig.getTopic());
        } catch (MqttException e) {
            log.error(e.getMessage(), e);
        }
    }
}
